/**
 *
 */
import { filterObj } from '@lone/lone-vue/src/utils/util';
import { deleteAction, getAction,postAction } from '@lone/lone-vue/src/api/manage'
import Vue from 'vue'
import { ACCESS_TOKEN } from "@/store/mutation-types"

export const LoneAsncTreeMixin = {
  data(){
    return {
      //token header
      tokenHeader: {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)},
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      treeSource:[],
      loadedKeys:[],
      autoLoad:true,
      checkedKeys:[],
      /* table加载状态 */
      loading:false,
      disabled:false,
      hiding: true,/*tree*/
      currSelected: {},
      selectedKeys: [],
      expandedKeys: [],
      autoExpandParent: true,
      checkStrictly:true,
      rightClickSelectedKey: '',
      keyWord: '',
      dbtouchtime:-1,
      searchData: []
    }
  },
  created() {
    if (this.autoLoad) {
      this.initData();
    }
  },
  mounted(){
  },
  methods: {
    //初始化加载方法
    initData (key = null, first = true, url = this.url.navList) {
      if(this.initDataFatherFunction){
        this.initDataFatherFunction();

      }else{
        getAction(url,{ key }).then((res) => {
          if (res.success) {
            this.treeSource = res.result
            this.loading = false
          }
        })
      }
    },

    //展开节点调用此方法
    onLoadData (treeNode,first = true, url = this.url.navList) {
      if(this.onLoadDataFatherFunction){
        this.onLoadDataFatherFunction(treeNode);
      }else{
        return new Promise((resolve) => {
          getAction(url,{ key:treeNode.dataRef.key }).then((res) => {
            if (res.success) {
              treeNode.dataRef.children = res.result;
              if(res.result && res.result.length > 0){
                this.treeSource = [...this.treeSource]
                resolve()
              }else{
                treeNode.setIsLeaf = true
              }
              this.loading = false
            }
          })
        })
      }
    },
    onCheck(checkedKeys, info){
      this.checkedKeys = checkedKeys
      if(this.onCheckKey== 'yes'){
        this.$emit("onCheck",checkedKeys)
      }
    },
    // 右键点击下拉框改变事件
    dropStatus(visible) {
      this.$emit('dropStatus',visible);
    },

    // 右键操作方法
    rightHandle(node) {
      this.$emit('rightHandle',node);
    },

    // 右键店家下拉关闭下拉框
    closeDrop() {
      this.$emit('closeDrop');
    },

    //刷新功能
    refresh() {
      if(this.refreshFatherFunction){
        this.refreshFatherFunction();
      }else{
        this.initData();
        this.treeSource=[];
        this.loading = true;
        this.onClearSelected();

      }
    },
    onexpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    //选中树节点
    onSelect(selectedKeys, e) {
      this.hiding = false
      let record = e.node.dataRef
      this.currSelected = Object.assign({}, record)
      this.model = this.currSelected
      this.selectedKeys = [record.key]
      //启用onSelect回调函数
      if(this.selectedKeyData == 'yes'){
        this.$emit("onSelect",record)
      }
      if(this.dbClick == 'Y'){
        if( this.dbtouchtime != -1 && (new Date().getTime() - this.dbtouchtime < 500) ){
          this.$emit("onDbSelect",this.selectedKeys[0],record)
        }else{
          this.dbtouchtime = new Date().getTime();
        }

      }
    },

    //获取选中节点内容
    getCurrSelectedTitle() {
      return !this.currSelected.title ? '' : this.currSelected.title
    },

    //取消选择
    onClearSelected() {
      this.hiding = true
      this.currSelected = {}
      this.selectedKeys = []
      this.expandedKeys = []
      this.checkedKeys = []
      //是否开启清除数据
      this.loading = false
      this.$emit("onClearSelected",this.selectedKeys)
    },
    getParentKey (key, tree) {
      let that = this, parentKey;
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
          if (node.children.some(item => item.key === key)) {
            parentKey = node.key;
          } else if (that.getParentKey(key, node.children)) {
            parentKey = that.getParentKey(key, node.children);
          }
        }
      }
      return parentKey;
    },
    //查询
    onSearch(value) {
      let that = this
      that.treeSource = [];
      that.keyWord = value;
      if(that.searchKeyWordFunction){
        that.searchKeyWordFunction(value)
      }else{
        if (value) {
           this.expandedKeys = this.searchData
            .map(item => {
              console.log(item.title.indexOf(value));
              console.log(item.title);
              if (item.title.indexOf(value) > -1) {
                return this.getParentKey(item.key, this.treeSource);
              }
              return null;
            })
            .filter((item, i, self) => item && self.indexOf(item) === i);

          Object.assign(this, {
            expandedKeys,
            keyWord: value,
            autoExpandParent: true,
          });
          /*getAction(this.url[0].search,{ keyWord:value }).then((res) => {
            if (res.success) {
              that.treeSource = res.result
              that.loading = false
            }
          })*/
        }else{
          that.initData()
        }
      }
    },

    //添加节点
    handleTreeAdd(num){
      if(this.addFatherFunction){
        this.addFatherFunction(num);
      }else{
        //selectedKey 为当前传入的节点
        if(num == 1){
          let selectedKey = this.selectedKeys[0];
          if(selectedKey == undefined || selectedKey == ''){
            this.$message.warning('请先选中一条记录!');
            return false;
          }
          this.$refs.modalForm.add(selectedKey);
        }else{
          this.$refs.modalForm.add();
        }
        this.$refs.modalForm.title = "新增";
      }

    },

    //修改节点
    handleTreeEdit(){
      if(this.editFatherFunction){
        this.editFatherFunction();
      }else{
        let temp = this.selectedKeys[0];
        if(temp == undefined || temp == ''){
          this.$message.warning('请先选中一条记录!');
          return false;
        }
        this.$refs.modalForm.edit(temp);
        this.$refs.modalForm.title = "编辑";
      }

    },

    //删除节点
    handleTreeDelete(){
      if(this.deleteFatherFunction){
        this.deleteFatherFunction()
      }else{
        let selectedKeys = this.selectedKeys[0];
        if(selectedKeys == undefined || selectedKeys == ''){
          this.$message.warning('请先选中一条记录!');
          return false;
        }
        if(!this.url.delete){
          this.$message.error("请设置url.delete属性!")
          return false
        }
        var that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            deleteAction(that.url.delete, {id: selectedKeys}).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.initData();
              } else {
                that.$message.warning(res.message);
              }
            });
          }
        });
      }

    },
  }

}